<template>
  <div class="contactTasks">
    <el-radio style="margin-right: -5px;"></el-radio>当前回访任务：{{ tskName }}
    <span style="margin-left: 50px;">选择主叫号码:</span>
    <el-cascader :options="options2iphone" clearable style="margin-left: 10px;width: 230px;"
      v-model="state.dataForm.caller"></el-cascader>
  </div>
  <div class="box" style=" margin-top: 20px;">
    <el-form label-width="80px" :model="state.dataForm" :rules="rules" ref="dataFormRef">
      <el-row>
        <label v-if="state.dataForm.mobileTip"
          style="color: red; font-size: 12px;height: 25px;margin-top: -10px;margin-left: 86px;">{{
            state.dataForm.mobileTip }}</label>
        <el-col>
          <el-form-item label="手机一" prop="mobile">
            <el-input v-model="state.dataForm.col1" placeholder="请输入"></el-input>
            <el-button type="primary" plain @click.stop="callPhone(state.dataForm.col1)"
              :disabled="state.tcccStates === 'offline' ? true : false">拨打电话</el-button>
          </el-form-item>
        </el-col>
        <label v-if="state.dataForm.mobile2Tip"
          style="color: red; font-size: 12px;height: 25px;margin-top: 0px;margin-left: 86px;">{{
            state.dataForm.mobile2Tip }}</label>
        <el-col>
          <el-form-item label="公司名称">
            <el-input v-model="state.dataForm.col2" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="姓名">
            <el-input v-model="state.dataForm.col3" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="部门">
            <el-input v-model="state.dataForm.col4" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="职务">
            <el-input v-model="state.dataForm.col5" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="邮箱">
            <el-input v-model="state.dataForm.name" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="电话号码">
            <el-input v-model="state.dataForm.ename" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="地址">
            <el-input v-model="state.dataForm.name" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="备注">
            <el-input v-model="state.dataForm.ename" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="主营产品">
            <el-input v-model="state.dataForm.col12" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="采购意向">
            <el-input v-model="state.dataForm.col25" placeholder="请输入"></el-input>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="联络结果">
            <el-input v-model="state.dataForm.result" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submission()">确认提交</el-button>
            <el-button type="primary" @click="next()">下一条</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import useView from "@/hooks/useView";
import baseService from "@/service/baseService";
import { nextTick, reactive, ref, toRefs, onMounted, onUnmounted, computed } from "vue";
import { useRoute } from 'vue-router';
import { ElMessage, } from "element-plus";
const view = reactive({
  dataForm: {
    loading: false,
    tskId: "",
    psnId: "",
    tskType: "",
    id: "",
    name: "",
    ename: "",
    city: '',
    curLinkId: '',
    col1: "",
    col2: "",
    col3: "",
    col4: "",
    col5: "",
    col12: "", //主营产品
    col25: "",  //采购意向
    result: "",
    telTip: '',
    tel2Tip: '',
    fax1: '',
    fax2: "",
    mobile: "",
    mobile2: "",
    mobileTip: '',
    mobile2Tip: '',
    email: "",
    email2: "",
    wechat: "",
    department: "",//部门
    position: "",//职务
    company: "",//公司
    website: "",//网址
    industry: "",//所属行业
    extField1: "",//标签一
    extField2: "",//标签二
    remark: "",//备注
    address: "",//地址
    address2: "",//英文地址
    category: "",//类别
    state: "",
    exhName: "",
    contactTag: "",
    productIntroduce: "",
    personName: "",//联络信息
    lrdRemark: "",//联络备注
    lrdResult: "",//联络结果
    lrdPlanTime: "",
    linkRecordDTOList: [] as any[],
    ifBlacked: false,//黑名单
    lrdLinkState: "",
    ifSkipCompany: false,//跳过同公司人员
    pageNum: 1,
    limit: 1,
    list: [],
    isPrincipal: false, // 只有负责人和管理员显示下一条
    newLinkRecordDTO: {
      tskId: "",
      psnId: "",
      lrdResult: '',
      lrdReason: '',
      lrdRemark: '',
      lrdCreateTime: '',
      tskName: '',
      personName: ''
    },
    caller: "",
  },
  tcccStates: "offline",
  tag2Selected: [] as any,
  total: 0
});


const dataFormRef = ref();

//下一条 新增变量，用于判断是否有下一条数据
const hasNextData = ref(false);


//初始化
const init = () => {
  Info();
  checkTcccStates();
  getTccPhone();
};

//接收过来的id
const route = useRoute();
const id = route.query.id;
const tskName = route.query.tskName;
const exhId = route.query.curExhId;
const pageNum1 = 1;
const pageNum = ref(1);

const rules = ref({
  mobile: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'change' },],
  mobile2: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'change' },],
  email: [{ pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱格式', trigger: 'change' },],
  email2: [{ pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱格式', trigger: 'change' },],
});

function validateEmail(email: string) {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return emailRegex.test(email);
}

//获取登录人是否为负责人
const Info = () => {
  baseService.get("noc/nocrepay/ifPrincipal/" + id).then((res) => {
    state.dataForm.isPrincipal = res.data
  });
};

//获取回显数据
let curLrdId: string;
baseService.get("/noc/nocrepay/repayCenter/" + id + "/" + pageNum1).then((res) => {
  if (res.code == 500) {
    hasNextData.value = false;
    ElMessage({
      message: '暂无数据',
      type: 'warning'
    });
    return;
  }
  if (res.data.list.length > 0) {
    hasNextData.value = true;
    const item = res.data.list[0];
    Object.assign(state.dataForm, item);
    curLrdId = item.curLrdId;
    state.dataForm.newLinkRecordDTO = {} as any;
    var extField2 = item.extField2;
    if (extField2) {
      let field2Str = extField2.split(",");
      state.tag2Selected = field2Str.map((item: any) => {
        return parseInt(item);
      });
      state.dataForm.extField2 = extField2.split(",");
    } else {
      state.dataForm.extField2 = [] as any;
    }
  }

  //isJoinMobile();
  //isJoinMobile2();
});


//联络提交
const submission = async () => {
  // 检查手机或电话至少有一项有值
  const hasMobileValue = state.dataForm.col1;
  if (!hasMobileValue) {
    ElMessage.error("手机号必须填写");
    return;
  }

  const valid = await dataFormRef.value.validate();
  if (!valid) {
    return false;
  }
  state.dataForm.extField2 = state.tag2Selected.join(",");
  state.dataForm.loading = true;
  const res = await baseService.post("/noc/nocrepay/saveContact", state.dataForm);
  if (res.code == 0) {
    await state.getDataList();  // 确保getDataList的异步操作完成
    ElMessage.success("联络提交成功");
    state.dataForm.loading = false;
    // 自动进入下一条, 页面置为0
    pageNum.value = 0;
    await next();  // 等待next函数里的异步操作完成
  } else {
    state.dataForm.loading = false;
  }
};

//下一条
const next = () => {
  if (hasNextData.value) {
    state.dataForm.loading = true;
    pageNum.value++;
    baseService.get("/noc/nocrepay/repayCenter/" + id + "/" + pageNum.value,
      { limit: state.dataForm.limit }
    ).then((res) => {
      Object.assign(state.dataForm, res.data.list[0]);
      // 重置联络结果
      state.dataForm.newLinkRecordDTO = {} as any;
      state.dataForm.ifSkipCompany = false;
      state.dataForm.loading = false;
      //判断手机号是否注册了预登记展会
      //isJoinMobile();
      //isJoinMobile2();
    }).catch((err) => {
      // 如果没有数据返回，说明没有下一条数据，设置hasNextData为false
      hasNextData.value = false;
      state.dataForm.loading = false;
    });
  }
};
//查询电话状态
const checkTcccStates = () => {
  /**
  baseService.get("tccc/getToken").then((res) => {
    // 如果返回200，说明当前用户未登录坐席
    if (res.data === '200') {
      return;
    }
    // 查询getSeatStatus接口
    baseService.get("tccc/getSeatStatus").then((r) => {
      if (r.data === 'offline') {
        state.tcccStates = "offline";
      } else {
        state.tcccStates = "online";
      }
    });
  });
  **/
};

let timer: any
onMounted(() => {
  checkTcccStates();
  timer = setInterval(checkTcccStates, 30000); // 每 30 秒调用一次
});

onUnmounted(() => {
  clearInterval(timer); // 组件卸载时清除定时器
});


const options2iphone = ref([]);

//获取电话号码
const getTccPhone = () => {
  baseService.get("/tccc/getTccPhone").then((res) => {
    options2iphone.value = res.data.list;
  });
};

/**
 * 拨打电话
 * @param phone
 */
const callPhone = (phone: any) => {
  if (!phone) {
    ElMessage.error("被叫号码不能为空！");
    return;
  }
  if (phone.length < 10) {
    ElMessage.error("被叫号码长度不对！");
    return;
  }
  //判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/
  var re = /^[0-9]+.?[0-9]*/;
  if (!re.test(phone)) {
    ElMessage.error("只能输数字！");
    return;
  }

  // 呼叫号码
  let callerPhoneNumber = state.dataForm.caller;
  let callOutParams: { phoneNumber: string; callerPhoneNumber?: string } = { phoneNumber: phone };
  // 有值的话，取第二个值并添加到参数中
  if (callerPhoneNumber) {
    callerPhoneNumber = callerPhoneNumber[1];
    callOutParams.callerPhoneNumber = "0086" + callerPhoneNumber;
  }

  //有值的话，取第二个值
  if (callerPhoneNumber) {
    callerPhoneNumber = callerPhoneNumber[1];
  }
  baseService.get("/tccc/checkcallPhone?callee=" + phone).then((res: any) => {
    if (res.count > 2) {
      ElMessage.error("同一个被叫号码当日限制外呼两次，请注意频次，避免投诉！");
      return;
    } else {
      //开始外呼
      const reponse = (window as any).tccc.callOut(callOutParams);
      reponse.then((res: any) => {
        baseService.post('/crm/crmtelhistory', { psnId: state.dataForm.id, tskId: id, sessionId: res.data.sessionId, timestamp: res.data.timestamp, exhId: exhId, lrdId: curLrdId }).then((res: any) => {
        })
      })
        .catch((err: any) => {
        })
    }
  });
};

//是否报名当前展会
const isJoinMobile = () => {
  state.dataForm.mobileTip = ''
  baseService.post("/crm/crmperson/isJoin", { phone: state.dataForm.mobile }).then((res) => {
    if (res.data > 0) {
      state.dataForm.mobileTip = '手机号' + state.dataForm.mobile + '已在当前展会预登记成功';
    }
  });
};

const isJoinMobile2 = () => {
  state.dataForm.mobile2Tip = ''
  baseService.post("/crm/crmperson/isJoin", { phone: state.dataForm.mobile2 }).then((res) => {
    if (res.data > 0) {
      state.dataForm.mobile2Tip = '手机号' + state.dataForm.mobile2Tip + '已在当前展会预登记成功';
    }
  });
};

const state = reactive({ ...useView(view), ...toRefs(view) });

const addKey = ref(0);
const addOrUpdateRef = ref();
const addOrUpdateHandle = (id?: number) => {
  addKey.value++;
  nextTick(() => {
    addOrUpdateRef.value.init(id);
  });
};

//页面进入执行
init();

</script>
<style lang="scss" scoped>
.contactTasks {
  font-size: 16px;
  font-weight: 600;
  color: #17B3A3;
}

.message {
  height: 20px;
  font-size: 14px;
  font-weight: 600;
  margin-left: -5px;
}

.el-col {
  margin-top: -3px;
}

.el-input {
  width: 200px;
}

.el-button {
  margin-left: 10px;
}
</style>
